﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SecureCommander.Core.UserManagement;
using System.Xml.Serialization;
using System.IO;
using SecureCommander.Helper;

namespace SecureCommander.DataAccess
{
    public class Data
    {
        private static string DATA_FILE_NAME = "data.xml";
        public DateTime LastUpdatedDate { get; set; }
        public List<UserInfo> Users;
        public static Data ApplicationData;

        public Data()
        {
            LastUpdatedDate = DateTime.Now;
            Users = new List<UserInfo>();
        }

        public void Save()
        {
            try
            {
                LastUpdatedDate = DateTime.Today;

                XmlSerializer serializer = new XmlSerializer(typeof(Data));
                TextWriter textWriter = new StreamWriter(DATA_FILE_NAME);
                serializer.Serialize(textWriter, this);
                textWriter.Close();
            }
            catch (Exception e)
            {
                FileHelper.ShowMessage("Can not save user data", System.Windows.MessageBoxImage.Warning);
            }
        }
        public static Data Load()
        {
            Data data = null;
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(Data));
                TextReader textReader = new StreamReader(DATA_FILE_NAME);
                data = (Data)serializer.Deserialize(textReader);
                textReader.Close();
            }
            catch
            {
                data = new Data();                
            }
            ApplicationData = data;
            return data;
        }
    }
}
